package ru.paswd.marketprice.storage.receipt.app.services;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ru.paswd.marketprice.storage.receipt.app.entity.FiscalId;
import ru.paswd.marketprice.storage.receipt.app.entity.Receipt;
import ru.paswd.marketprice.storage.receipt.app.exceptions.ReceiptAlreadyExistsException;
import ru.paswd.marketprice.storage.receipt.app.exceptions.ReceiptNotFoundException;
import ru.paswd.marketprice.storage.receipt.app.repositories.ReceiptsRepository;

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ReceiptService {
    private final ReceiptsRepository receiptsRepository;

    public Page<Receipt> getAllReceipts(Pageable pageable) {
        return receiptsRepository.findAll(pageable);
    }

    public Receipt getReceiptByParams(String fiscalNumber, String fiscalSign, String fiscalDocumentNumber) {
        FiscalId fiscalId = new FiscalId(fiscalNumber, fiscalSign, fiscalDocumentNumber);
        return receiptsRepository.findFirstByFiscalId(
                fiscalId)
                .orElseThrow(() -> new ReceiptNotFoundException(fiscalId));
    }

    public void addReceipt(Receipt receipt) {
        if (receiptsRepository.existsByFiscalId(receipt.getFiscalId())) {
            throw new ReceiptAlreadyExistsException(
                    receipt.getFiscalId());
        }

        receiptsRepository.save(receipt);
    }

    public void updateReceipt(Receipt receipt) {

        Receipt existingReceipt = receiptsRepository.findFirstByFiscalId(receipt.getFiscalId())
                .orElseThrow(() -> new ReceiptNotFoundException(receipt.getFiscalId()));

        existingReceipt.setCompany(receipt.getCompany());
        existingReceipt.setDateTime(receipt.getDateTime());
        existingReceipt.setTotalSum(receipt.getTotalSum());

        receiptsRepository.save(existingReceipt);
    }

    @Transactional
    public void removeReceipt(FiscalId fiscalId) {
        if (!receiptsRepository.existsByFiscalId(fiscalId))
            throw new ReceiptNotFoundException(fiscalId);

        receiptsRepository.deleteAllByFiscalId(fiscalId);
    }
}
